<template>
  <el-dialog v-model="dialogTableVisible" title="sku管理" width="1000">
    <el-button type="primary" style="margin-bottom: 10px" @click="addSku">+新增sku</el-button>

    <!-- 表格展示 -->
    <el-table v-loading="loading" :data="skuList" style="width: 100%">
      <el-table-column type="index" label="序号" width="100" />
      <el-table-column label="图片">
        <template #default="scope">
          <img :src="scope.row.picture" alt="图片" style="width: 100px; height: 100px" />
        </template>
      </el-table-column>
      <el-table-column prop="skuCode" label="sku编号" />
      <el-table-column prop="price" label="价格" />
      <el-table-column prop="inventory" label="库存" />
      <el-table-column label="规格">
        <template #default="scope">
          <div v-for="skuSpec in scope.row.skuSpecList" :key="skuSpec.id">
            <span>{{ skuSpec.name }}：{{ skuSpec.valueName }}</span>
          </div>
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <!-- 编辑按钮 -->
          <el-button type="primary" @click="editSku(row)">
            <el-icon>
              <Edit />
            </el-icon>
          </el-button>

          <!-- 删除确认框 -->
          <el-popconfirm title="确认删除吗?" confirm-button-text="确认" cancel-button-text="取消"
            @confirm="deleSku(row.id)">
            <template #reference>
              <el-button type="danger">
                <el-icon>
                  <Delete />
                </el-icon>
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>

      <!-- 无数据提示 -->
      <template #empty>
        <el-empty description="没有数据"></el-empty>
      </template>
    </el-table>
  </el-dialog>

  <SkuEdit ref="dialog" @success="onSuccess" />
</template>

<script setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { getSkuAPI, deleSkuAPI } from "@/apis/goods.js";
import SkuEdit from "./SkuEdit.vue";

// 状态定义
const dialogTableVisible = ref(false);
const dialog = ref(null);
const loading = ref(false);
const skuList = ref([]);
const specList = ref([]);
const goodsId = ref(null);

// 事件定义
const emit = defineEmits(["success"]);

// 方法定义
const addSku = () => {
  dialog.value.open({}, goodsId.value, specList.value);
};

const getSku = async () => {
  const res = await getSkuAPI(goodsId.value);
  skuList.value = res.data;
};

const editSku = (row) => {
  dialog.value.open(row, goodsId.value, specList.value);
};

const deleSku = async (id) => {
  const res = await deleSkuAPI(id);
  if (res.code === 1) {
    ElMessage.success("删除成功");
    getSku();
  }
};

const onSuccess = async () => {
  getSku();
};

// 暴露给外部的方法
const open = async (id, specs) => {
  goodsId.value = id;
  specList.value = specs;
  getSku();
  loading.value = false;
  dialogTableVisible.value = true;
};

// 暴露给父组件的方法
defineExpose({
  open,
});
</script>